"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var milvus2_sdk_node_1 = require("@zilliz/milvus2-sdk-node");
var vmo_request_1 = require("vmo-request");
var readline_1 = require("readline");
// 创建 Milvus 客户端
var milvusClient = new milvus2_sdk_node_1.MilvusClient({
    address: 'localhost:19530',
});
// 创建请求实例
var vmoRequest = new vmo_request_1.VmoRequest({
    baseURL: 'http://localhost:11434',
    timeout: 30000,
}, true);
// 创建 readline 接口
var rl = readline_1.default.createInterface({
    input: process.stdin,
    output: process.stdout
});
/**
 * 生成文本嵌入
 */
function generateEmbedding(text) {
    return __awaiter(this, void 0, void 0, function () {
        var response, error_1;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, vmoRequest.request({
                            url: '/api/embeddings',
                            method: 'post',
                            data: {
                                model: 'bge-m3',
                                prompt: text,
                            }
                        })];
                case 1:
                    response = _b.sent();
                    if (!((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.embedding) || !Array.isArray(response.data.embedding)) {
                        throw new Error('生成嵌入失败：响应格式错误');
                    }
                    return [2 /*return*/, response.data.embedding];
                case 2:
                    error_1 = _b.sent();
                    console.error('生成嵌入失败:', error_1);
                    throw error_1;
                case 3: return [2 /*return*/];
            }
        });
    });
}
/**
 * 清空集合
 */
function clearCollection() {
    return __awaiter(this, void 0, void 0, function () {
        var error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, milvusClient.dropCollection({
                            collection_name: 'text_embeddings'
                        })];
                case 1:
                    _a.sent();
                    console.log('集合已清空');
                    return [3 /*break*/, 3];
                case 2:
                    error_2 = _a.sent();
                    console.error('清空集合失败:', error_2);
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    });
}
/**
 * 添加向量数据
 */
function addVectorData() {
    return __awaiter(this, void 0, void 0, function () {
        var _this = this;
        return __generator(this, function (_a) {
            try {
                rl.question('请输入要添加的文本: ', function (text) { return __awaiter(_this, void 0, void 0, function () {
                    var embedding, error_3;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 3, , 4]);
                                return [4 /*yield*/, generateEmbedding(text)];
                            case 1:
                                embedding = _a.sent();
                                return [4 /*yield*/, milvusClient.insert({
                                        collection_name: 'text_embeddings',
                                        fields_data: [{
                                                text: text,
                                                embedding: embedding,
                                            }],
                                    })];
                            case 2:
                                _a.sent();
                                console.log('向量数据添加成功');
                                return [3 /*break*/, 4];
                            case 3:
                                error_3 = _a.sent();
                                console.error('添加向量数据失败:', error_3);
                                return [3 /*break*/, 4];
                            case 4:
                                showMenu();
                                return [2 /*return*/];
                        }
                    });
                }); });
            }
            catch (error) {
                console.error('操作失败:', error);
                showMenu();
            }
            return [2 /*return*/];
        });
    });
}
/**
 * 查询向量数据
 */
function searchVectors() {
    return __awaiter(this, void 0, void 0, function () {
        var _this = this;
        return __generator(this, function (_a) {
            try {
                rl.question('请输入查询文本: ', function (queryText) { return __awaiter(_this, void 0, void 0, function () {
                    var queryEmbedding, results, error_4;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 3, , 4]);
                                return [4 /*yield*/, generateEmbedding(queryText)];
                            case 1:
                                queryEmbedding = _a.sent();
                                return [4 /*yield*/, milvusClient.search({
                                        collection_name: 'text_embeddings',
                                        vector: queryEmbedding,
                                        output_fields: ['text'],
                                        limit: 5,
                                        metric_type: 'COSINE',
                                    })];
                            case 2:
                                results = _a.sent();
                                console.log('查询结果:', JSON.stringify(results, null, 2));
                                return [3 /*break*/, 4];
                            case 3:
                                error_4 = _a.sent();
                                console.error('查询失败:', error_4);
                                return [3 /*break*/, 4];
                            case 4:
                                showMenu();
                                return [2 /*return*/];
                        }
                    });
                }); });
            }
            catch (error) {
                console.error('操作失败:', error);
                showMenu();
            }
            return [2 /*return*/];
        });
    });
}
/**
 * 显示菜单
 */
function showMenu() {
    var _this = this;
    console.log('\n=== Milvus 向量数据库管理工具 ===');
    console.log('1. 清空集合');
    console.log('2. 添加向量数据');
    console.log('3. 查询向量数据');
    console.log('0. 退出');
    rl.question('请选择操作: ', function (answer) { return __awaiter(_this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = answer;
                    switch (_a) {
                        case '1': return [3 /*break*/, 1];
                        case '2': return [3 /*break*/, 3];
                        case '3': return [3 /*break*/, 5];
                        case '0': return [3 /*break*/, 7];
                    }
                    return [3 /*break*/, 8];
                case 1: return [4 /*yield*/, clearCollection()];
                case 2:
                    _b.sent();
                    showMenu();
                    return [3 /*break*/, 9];
                case 3: return [4 /*yield*/, addVectorData()];
                case 4:
                    _b.sent();
                    return [3 /*break*/, 9];
                case 5: return [4 /*yield*/, searchVectors()];
                case 6:
                    _b.sent();
                    return [3 /*break*/, 9];
                case 7:
                    rl.close();
                    process.exit(0);
                    return [3 /*break*/, 9];
                case 8:
                    console.log('无效的选择，请重试');
                    showMenu();
                    _b.label = 9;
                case 9: return [2 /*return*/];
            }
        });
    }); });
}
// 启动程序
showMenu();
